package com.loan.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.params.CoreConnectionPNames;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.loan.model.Data;

@SuppressWarnings("deprecation")
public class Http {  

	public static String post(String url) throws Exception{  
		return Http.post(url,Data.put("",""));
	}
	
	public static String post(String url, Map<Object,Object> map) throws Exception{  
    	StringBuffer sb = new StringBuffer();
    	PostMethod xmlpost;
 	    int statusCode = 0;
 	    HttpClient httpclient = new HttpClient();
 	    httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 200000);
 	    xmlpost = new PostMethod(url);
 	    httpclient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
        try{
        	//组合请求参数
        	List<NameValuePair> list=new ArrayList<NameValuePair>();
        	for(Object key : map.keySet()) {
				NameValuePair nvp=new NameValuePair(String.valueOf(key),String.valueOf(map.get(key)));
				list.add(nvp);
        	}
			NameValuePair[] nvps=new NameValuePair[list.size()];
        	xmlpost.setRequestBody(list.toArray(nvps)); 
        	statusCode = httpclient.executeMethod(xmlpost);
            if(statusCode<HttpURLConnection.HTTP_OK || statusCode>=HttpURLConnection.HTTP_MULT_CHOICE){
                //System.err.println("失败返回码[" + statusCode + "]"); 
                throw new Exception("请求接口失败，失败码[ "+ statusCode +" ]");
            }
	    	String result = "";
	    	BufferedReader br = new BufferedReader(new InputStreamReader(xmlpost.getResponseBodyAsStream(), "UTF-8"));
            while((result=br.readLine())!=null) {
            	sb.append(result);
            }
        }catch(IOException e){
            e.printStackTrace();
            System.err.println(e.toString());
            throw e;
        }
        return sb.toString();
    } 
	
	public static JSONObject post(String url,JSONObject json){  
		org.apache.http.client.HttpClient httpClient = HttpClientBuilder.create().build();
		JSONObject res = null;  
		try {
		    HttpPost request = new HttpPost(url);
		    StringEntity params =new StringEntity(json.toJSONString(),Charset.forName("UTF-8"));
		    request.addHeader("content-type", "application/json;charset=UTF-8");
		    request.setEntity(params);
		    HttpResponse response = httpClient.execute(request);
            if(response.getStatusLine().getStatusCode()==200){  
                HttpEntity entity = response.getEntity();  
                ContentType charset = ContentType.getOrDefault(entity);
                BufferedReader streamReader = new BufferedReader(new InputStreamReader(entity.getContent(),charset.getCharset())); 
                StringBuilder responseStrBuilder = new StringBuilder();
                String inputStr;
                while ((inputStr = streamReader.readLine()) != null){
                    responseStrBuilder.append(inputStr);
                }
                res = JSON.parseObject(responseStrBuilder.toString());
            }  
		}catch (Exception e) {
			e.printStackTrace();
		} finally {
		}
		return res;
    } 
	
	
    /** 
     * 发送GET请求 
     *  
     * @param url 
     *            目的地址 
     * @param parameters 
     *            请求参数，Map类型。 
     * @return 远程响应结果 
     */  
    public static String get(String url, Map<String, String> parameters) { 
        String result="";
        BufferedReader in = null;// 读取响应输入流  
        StringBuffer sb = new StringBuffer();// 存储参数  
        String params = "";// 编码之后的参数
        try {
            // 编码请求参数  
            if(parameters.size()==1){
                for(String name:parameters.keySet()){
                    sb.append(name).append("=").append(
                            java.net.URLEncoder.encode(parameters.get(name),  
                            "UTF-8"));
                }
                params=sb.toString();
            }else{
                for (String name : parameters.keySet()) {  
                    sb.append(name).append("=").append(  
                            java.net.URLEncoder.encode(parameters.get(name),  
                                    "UTF-8")).append("&");  
                }  
                String temp_params = sb.toString();  
                params = temp_params.substring(0, temp_params.length() - 1);  
            }
            String full_url = url + "?" + params; 
            System.out.println(full_url); 
            // 创建URL对象  
            java.net.URL connURL = new java.net.URL(full_url);  
            // 打开URL连接  
            java.net.HttpURLConnection httpConn = (java.net.HttpURLConnection) connURL  
                    .openConnection();  
            // 设置通用属性  
            httpConn.setRequestProperty("Accept", "*/*");  
            httpConn.setRequestProperty("Connection", "Keep-Alive");  
            httpConn.setRequestProperty("User-Agent",  
                    "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");  
            // 建立实际的连接  
            httpConn.connect();  
            // 响应头部获取  
            //Map<String, List<String>> headers = httpConn.getHeaderFields();  
            // 遍历所有的响应头字段  
           /** for (String key : headers.keySet()) {  
                System.out.println(key + "\t：\t" + headers.get(key));  
            }  */
            // 定义BufferedReader输入流来读取URL的响应,并设置编码方式  
            in = new BufferedReader(new InputStreamReader(httpConn  
                    .getInputStream(), "UTF-8"));  
            String line;  
            // 读取返回的内容  
            while ((line = in.readLine()) != null) {  
                result += line;  
            }  
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {  
                if (in != null) {  
                    in.close();  
                }  
            } catch (IOException ex) {  
                ex.printStackTrace();  
            }  
        }
        return result ;
    }  
	
	/** 
     * 发送HttpPost请求 
     *  
     * @param strURL 
     *            服务地址 
     * @param params 
     *  
     * @return 成功:返回json字符串<br/> 
     */  
    public static String jsonPost(String strURL, Map<String, String> params) {  
        try {  
            URL url = new URL(strURL);// 创建连接  
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();  
            connection.setDoOutput(true);  
            connection.setDoInput(true);  
            connection.setUseCaches(false);  
            connection.setInstanceFollowRedirects(true);  
            connection.setRequestMethod("POST"); // 设置请求方式  
            connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式  
            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式  
            connection.connect();  
            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码  
            out.append(JSONObject.toJSONString(params));  
            out.flush();  
            out.close();  
  
            int code = connection.getResponseCode();  
            InputStream is = null;  
            if (code == 200) {  
                is = connection.getInputStream();  
            } else {  
                is = connection.getErrorStream();  
            }  
  
            // 读取响应  
            int length = (int) connection.getContentLength();// 获取长度  
            if (length != -1) {  
                byte[] data = new byte[length];  
                byte[] temp = new byte[512];  
                int readLen = 0;  
                int destPos = 0;  
                while ((readLen = is.read(temp)) > 0) {  
                    System.arraycopy(temp, 0, data, destPos, readLen);  
                    destPos += readLen;  
                }  
                String result = new String(data, "UTF-8"); // utf-8编码  
                return result;  
            }  
  
        } catch (IOException e) {  

        }  
        return "error"; // 自定义错误信息  
    } 
}
